package link_list;

import link_list.node.SinglyListNode;

/**
 * 链表中的部分反转
 */

public class LinkedListPartialInversion {

    public static void main(String[] args) {
//        ListNode first = new ListNode(3);
//        first.next=new ListNode(2);
//        first.next.next=new ListNode(1);
//        first.next.next.next=new ListNode(5);
//        first.next.next.next.next=new ListNode(8);
//        first.next.next.next.next.next=new ListNode(7);
//        first.next.next.next.next.next.next=new ListNode(9);
//        ListNode result = splitList(first,2,5);
//        while (result !=null){
//            // 原顺序3215879
//            System.out.print(result.val);
//            result = result.next;
//        }
        SinglyListNode first = new SinglyListNode(1);
        first.next=new SinglyListNode(2);
        first.next.next=new SinglyListNode(3);
        first.next.next.next=new SinglyListNode(4);
        first.next.next.next.next=new SinglyListNode(5);
        SinglyListNode result = splitList(first,2,4);
        while (result !=null){
            // 原顺序3215879
            System.out.print(result.val);
            result = result.next;
        }

    }
    public static void reverseList(SinglyListNode head, SinglyListNode curr, SinglyListNode behind){
        SinglyListNode post = null,pre = behind;
        while(curr != null){
            post = curr.next;
            curr.next = pre;
            pre = curr;
            curr = post;
        }
        head.next = pre;

    }

    public static SinglyListNode splitList(SinglyListNode first, int pre, int post){
        SinglyListNode result[] = new SinglyListNode[3];
        result[0] = first;
        int i =2;
        for (;i<pre;i++){
            result[0]=result[0].next;
        }
        result[1]=result[0].next;
        for (;i<post;i++){
            result[1]=result[1].next;
        }

        if(result[1] != null){
            result[2]=result[1].next;
            result[1].next = null;
        }
        reverseList(result[0],result[0].next,result[2]);
        return first;
    }
}
